package cn.qg.auth.controller;

import cn.qg.auth.exception.LoginFailedException;
import cn.qg.auth.service.qguser.QgUserService;
import cn.qg.auth.service.token.TokenService;
import cn.qg.beans.dto.Dto;
import cn.qg.beans.pojo.QgUser;
import cn.qg.beans.vo.QgUserTokenVO;
import cn.qg.common.DtoUtil;
import cn.qg.common.EmptyUtils;
import cn.qg.common.ErrorCode;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 用户登录注销控制器
 * @auth amwdx
 * 2019/5/11 0011 15:46
 */

@RestController
@RequestMapping(value = "/api")
public class LoginController {

    @Resource
    private QgUserService qgUserService;
    @Resource
    private TokenService tokenService;

/**
 * 用户登录
 */
@RequestMapping(value = "/dologin",method = RequestMethod.POST,produces = {"application/json"})
    public Dto doLogin(@RequestParam String phone,@RequestParam String password)throws Exception{
        try {
            // 1.判断用户名或密码不能为空
            if (EmptyUtils.isEmpty(phone)||(EmptyUtils.isEmpty(password))){
                throw new LoginFailedException("用户名或密码不能为空");
            }
            // 2.用户登录验证
            QgUser qgUser = qgUserService.login(phone,password);
            // 3.验证是否存在该用户
            if (EmptyUtils.isEmpty(qgUser)){
                throw new LoginFailedException("用户名或者密码错误");
            }
            // 4.开始生成token
            String token=tokenService.generateToken(qgUser);
            // 5.缓存到Redis
            tokenService.saveToken(token,qgUser);
            // 6.返回Token相关信息给前端
            QgUserTokenVO qgUserTokenVO = new QgUserTokenVO(token,
                    new Date().getTime() + TokenService.TOKEN_EXPIRE_TIME * 1000,
                    new Date().getTime());
            return DtoUtil.returnDataSuccess(qgUserTokenVO);
        }catch (LoginFailedException e){
           return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_AUTHENTICATION_FAILED);
        }catch (Exception e){
            return DtoUtil.returnFail("用户登录失败,请重试",ErrorCode.AUTH_UNKNOWN);
        }

        }
}
